package lab.jsp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lab.bmp.artist.Artist;
import lab.bmp.artist.ArtistPK;
import lab.bmp.genre.Genre;
import lab.bmp.genre.GenrePK;
import lab.bmp.studio.Studio;
import lab.bmp.studio.StudioPK;
import lab.bmp.track.Track;
import lab.bmp.track.TrackPK;
import lab.domain.ChangableHashSet;
import lab.domain.SoundRecordingStudio;

/**
 *
 * @author Smike
 */
public class EditTrack extends AbstractJSP<Track> {

    public static final String ID = "id";
    public static final String NAME = "name";
    public static final String YEAR = "year";
    public static final String LENGTH = "length";
    public static final String STUDIO = "studio";
    public static final String ARTIST_COUNT = "artists";
    public static final String GENRES_COUNT = "genres";
    public static final String ARTIST = "artists[%d]";
    public static final String GENRE = "genres[%d]";
    
    Track track;

    @Override
    public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // do nothing
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter(ID);
        if (id != null) {
            int value = Integer.valueOf(id);
            if (value >= 0) {
                track = dao.findTrack(new TrackPK(value));
            }
        } else {
            track = null;
        }
        super.doGet(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter(ID);
        if (id != null) {
            int value = Integer.valueOf(id);
            if (value >= 0) {
                track = (Track) PortableRemoteObject.narrow(dao.findTrack(new TrackPK(value)), Track.class);
            } else {
                track = null;
            }
        } else {
            throw new IllegalArgumentException();
        }
        try {
            if (request.getParameter("save") != null) {
                
                String name = request.getParameter(NAME);
                int year = Integer.parseInt(request.getParameter(YEAR));
                int length = Integer.parseInt(request.getParameter(LENGTH));
                int studioId = Integer.parseInt(request.getParameter(STUDIO));
                
                ChangableHashSet<lab.domain.Artist> artists = new ChangableHashSet<lab.domain.Artist>();
                int artistCount = Integer.parseInt(request.getParameter(ARTIST_COUNT));
                for (int i = 0; i < artistCount; i++) {
                    lab.domain.Artist artist = new lab.domain.Artist();
                    artist.setId(Integer.parseInt(request.getParameter(String.format(ARTIST, i))));
                    artists.add(artist);
                }
                
                ChangableHashSet<lab.domain.Genre> genres = new ChangableHashSet<lab.domain.Genre>();
                int genreCount = Integer.parseInt(request.getParameter(GENRES_COUNT));
                for (int i = 0; i < genreCount; i++) {
                    lab.domain.Genre genre = new lab.domain.Genre();
                    genre.setId(Integer.parseInt(request.getParameter(String.format(GENRE, i))));
                    genres.add(genre);
                }
                
                if (track != null) {
                    track.setName(name);
                    track.setYear(year);
                    track.setLength((long)length);
                    Collection<ArtistPK> as = new ArrayList<ArtistPK>();
                    for (lab.domain.Artist a : artists) {
                        as.add(new ArtistPK(a.getId()));
                    }
                    track.setArtists(as);
                    Collection<GenrePK> gs = new ArrayList<GenrePK>();
                    for (lab.domain.Genre a : genres) {
                        gs.add(new GenrePK(a.getId()));
                    }
                    track.setGenres(gs);
                    track.setStudio(new StudioPK(studioId));
                } else {                    
                    lab.domain.Track t = new lab.domain.Track();
                    t.setName(name);
                    t.setArtists(artists);
                    t.setGenres(genres);
                    SoundRecordingStudio s = new SoundRecordingStudio();
                    s.setId(studioId);
                    t.setSoundRecordingStudio(s);
                    dao.insertTrack(t);
                }
            } else if (request.getParameter("delete") != null) {
                if (track.getId() != null) {
                    track.remove();
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(EditTrack.class.getName()).log(Level.SEVERE, null, ex);
        }
        response.sendRedirect("tracks.jsp");
    }

    @Override
    protected Track getData() {
        return track;
    }
    
    public Collection<Artist> getArtists() {
        try {
            return dao.findArtists();
        } catch (Exception ex) {
            Logger.getLogger(EditTrack.class.getName()).log(Level.SEVERE, null, ex);
            return Collections.EMPTY_LIST;
        }
    }
    
    public Collection<Genre> getGenres() {
        try {
            return dao.findGenres();
        } catch (Exception ex) {
            Logger.getLogger(EditTrack.class.getName()).log(Level.SEVERE, null, ex);
            return Collections.EMPTY_LIST;
        }
    }
    
    public Collection<Studio> getStudios() {
        try {
            return dao.findStudios();
        } catch (Exception ex) {
            Logger.getLogger(EditTrack.class.getName()).log(Level.SEVERE, null, ex);
            return Collections.EMPTY_LIST;
        }
    }
    
    
}
